package com.lwb.serviceacl.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lwb.serviceacl.entity.Permission;
import com.lwb.serviceacl.entity.RolePermission;
import com.lwb.serviceacl.entity.User;
import com.lwb.serviceacl.helper.MemuHelper;
import com.lwb.serviceacl.helper.PermissionHelper;
import com.lwb.serviceacl.mapper.PermissionMapper;
import com.lwb.serviceacl.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lwb.serviceacl.service.RolePermissionService;
import com.lwb.serviceacl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-12-16
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {


    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private UserService userService;

    @Override
    public List<Permission> queryAllMenuGuli() {
        //通过排序查询出所有的菜单
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        List<Permission> permissionList = baseMapper.selectList(queryWrapper);

        List<Permission> permissions = PermissionHelper.bulid(permissionList);


        return permissions;
    }

    //递归删除菜单
    @Override
    public void removeChildByIdGuli(String id) {
        //1. 创建List集合，用于封装所有删除菜单的id值
        List<String> idList = new ArrayList<>();
        this.selectPermissionChildById(id,idList);
        //把当前id封装到list里面
        idList.add(id);
        baseMapper.deleteBatchIds(idList);
    }

    //2 根据当前菜单id，查询菜单里面子菜单id，封装到list集合
    private void selectPermissionChildById(String id, List<String> idList) {
        //查询菜单里面子菜单id
        QueryWrapper<Permission>  wrapper = new QueryWrapper<>();
        wrapper.eq("pid",id);
        wrapper.select("id");
        List<Permission> childIdList = baseMapper.selectList(wrapper);
        //把childIdList里面菜单id值获取出来，封装idList里面，做递归查询
        childIdList.stream().forEach(item -> {
            //封装idList里面
            idList.add(item.getId());
            //递归查询
            this.selectPermissionChildById(item.getId(),idList);
        });
    }

    //给角色分配菜单
    @Override
    public void saveRolePermissionRealtionShipGuli(String roleId, String[] permissionId) {

        //roleId角色id
        //permissionId菜单id 数组形式
        //1 创建list集合，用于封装添加数据
        List<RolePermission> rolePermissionList = new ArrayList<>();
        //遍历所有菜单数组
        for(String perId : permissionId) {
            //RolePermission对象
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(perId);
            //封装到list集合
            rolePermissionList.add(rolePermission);
        }
        //添加到角色菜单关系表
        rolePermissionService.saveBatch(rolePermissionList);


    }

    //根据角色获取菜单
    @Override
    public List<Permission> selectAllMenu(String roleId) {
        List<Permission> permissions = baseMapper.selectList(new QueryWrapper<Permission>().orderByAsc("CAST(id AS SIGNED)"));
        List<RolePermission> rolePermissions = rolePermissionService.list(new QueryWrapper<RolePermission>().eq("role_id", roleId));
        for (int i=0;i<permissions.size();i++) {
            Permission permission = permissions.get(i);
            for (int j=0;j<rolePermissions.size();j++){
                RolePermission rolePermission = rolePermissions.get(j);
                if(permission.equals(rolePermission.getPermissionId())){
                    permission.setSelect(true);
                }
            }
        }

        List<Permission> permissionList = PermissionHelper.bulid(permissions);
        return permissionList;
    }

    @Override
    public List<String> selectPermissionValueByUserId(String id) {
        List<String> selectPermissionValueList = null;
        if(this.isSysAdmin(id)) {
            //如果是系统管理员，获取所有权限
            selectPermissionValueList = baseMapper.selectAllPermissionValue();
        } else {
            selectPermissionValueList = baseMapper.selectPermissionValueByUserId(id);
        }
        return selectPermissionValueList;
    }

    @Override
    public List<JSONObject> selectPermissionByUserId(String id) {
        List<Permission> selectPermissionList = null;
        if(this.isSysAdmin(id)) {
            //如果是超级管理员，获取所有菜单
            selectPermissionList = baseMapper.selectList(null);
        } else {
            selectPermissionList = baseMapper.selectPermissionByUserId(id);
        }

        List<Permission> permissionList = PermissionHelper.bulid(selectPermissionList);
        List<JSONObject> result = MemuHelper.bulid(permissionList);
        return result;
    }

    /**
     * 判断用户是否系统管理员
     * @param userId
     * @return
     */
    private boolean isSysAdmin(String id) {
        User user = userService.getById(id);

        if(null != user && "admin".equals(user.getUsername())) {
            return true;
        }
        return false;
    }
}
